const cart = {
  namespaced: true,

  state: {
    products: []
  },

  mutations: {
    setProducts(state, product) {
      const p = state.products.find((value) => value.id === product.id)
      if (p) {
        p.quantity++
      } else {
        state.products.push({
          ...product,
          quantity: 1
        })
      }
    }
  },

  actions: {
    addProductToCart({ commit, dispatch }, product) {
      // console.log(context)
      commit('setProducts', product)
      // 库存减一
      dispatch(
        'product/decrementInventory', 
        product, 
        { root: true }
      )
    }
  },

  getters: {
    totalPrice(state) {
      return state.products.reduce((sum, p) => {
        sum += p.price * p.quantity
        return sum
      }, 0)
    }
  }
}

export default cart